<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\severs\PrintTemplateSevers;
use think\facade\Db;
use think\facade\View;

class PrintTemplate extends BaseController
{
    protected $title='打印模板';
    protected $table='print_template';
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['status','>',-1];
            if (isset($param['name'])&&$param['name']){
                $where[]=['name','like',"%".$param['name'].'%'];
            }
            if (isset($param['type'])&&$param['type']){
                $where[]=['type','=',$param['type']];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->where($where)
                ->field("*")
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }

    }

    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $param=$this->param;
            $param['update_time']=time();
            $meUrl=Db::name('admin_rule')->where('id',$this->param['type'])->value('src');
            $meArr=explode('/',$meUrl);
//            $param['baseTemp']=PrintTemplateSevers::creatData();
//            $param['detailTemp']=PrintTemplateSevers::createMx();
           if (count($meArr)<3){
               return to_assign(1,'操作有误');
           }
//           halt($param);
           $pTag=$meArr[0].'/'.$meArr[1];
           $param['pTag']=strtolower($pTag);
            if ($param['id'] > 0) {
                Db::name($this->table)->strict(false)->field(true)->update($param);
                add_log('edit', $param['id'], $param,$this->title);
            } else {
                $tblBody=Db::name($this->table)->where('pTag',$param['pTag'])
                    ->where('tplBody','<>','')
                    ->where('baseTemp','<>','')
                    ->where('detailTemp','<>','')
                    ->order('id DESC')->limit(1)->find();
                $param['tplBody']='{"panels":[{"index":0,"paperType":"A4","height":297,"width":210,"paperHeader":43.5,"paperFooter":801,"printElements":[],"paperNumberLeft":565,"paperNumberTop":819}]}';
                if ($tblBody){
                    $param['tplBody']=$tblBody['tplBody'];
                    $param['baseTemp']=$tblBody['baseTemp'];
                    $param['detailTemp']=$tblBody['detailTemp'];
                }
                $param['createId']=$this->uid;
                $param['did']=$this->did;
                $param['create_time'] = time();
                $rid = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                add_log('add', $rid, $param,$this->title);
            }
            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->find();
                View::assign('detail', $detail);
            }
            View::assign('id', $id);

            $typeList=getPrintType();
            View::assign('typeList',$typeList);
            return view('form');
        }
    }
    public function delete()
    {

        if (request()->isDelete()) {
            $id = get_params("id");
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }
    public function doCheck()
    {
        $param = get_params();
        $param['update_time']=time();
        $res = Db::name($this->table)->strict(false)->field('id,status,update_time')->update($param);
        if ($res) {
            if($param['status'] == 2){
                add_log('disable', $param['id'], $param,$this->title);
            }
            else if($param['status'] == 1){
                add_log('recovery', $param['id'], $param,$this->title);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    public function design($id='')
    {
        if ($this->request->post()){
            $param=$this->param;
            Db::name($this->table)->strict(false)->field(true)->update($param);
            add_log('edit', $param['id'], $param,$this->title);

            return to_assign();
        }else{
            $info=Db::name($this->table)->where('id',$id)->find();
            $json  = "new hiprint.PrintElementTypeGroup('字段', [" . PHP_EOL;
            $tables=['sale_contract','sale_contract_detail','material_dossier'];
            $prefix=config('database.connections.mysql.prefix');
            $basic = $detail = '';
            if ($info['pTag']=='home/salecontract'){
                $temp=PrintTemplateSevers::createSalContractData();
                $basic=$temp['baseTemp'];
                $detail=$temp['detailTemp'];
            }
//            elseif ($info['pTag']=='home/buycontract'){
//
//            }
            else{
                $basic=$info['baseTemp'];
                $detail=$info['detailTemp'];
            }


//            if ($info){
//                $basic=$info['baseTemp'];
//                $detail=$info['detailTemp'];
////                halt($detail);
//            }
//            foreach ($tables as $item){
//                $array=Db::getFields($prefix.$item);
//                if (!str_contains($item, 'detail')) {
//                    $basicTemp = '';
//                    foreach ($array as $v) {
//                        $v['title']=$v['comment'];
//                        $v['field']=$v['name'];
//                        $dd=[];
//                        if ($v['title']) {
//                            $dd['text']  = $v['title'];
//                            $dd['title'] = '标题：' . $v['title'] . '，字段名：' . $v['field'];
//                            $dd['tid']   = 'leftModule.' . ($v['field'] === 'text' ? $v['field'] . 's' : $v['field']);
//                            unset($v['field'],);
//                            $basicTemp .= json_encode($dd,320) . ",\n";
//                        }
//                    }
//                    $basic .= rtrim($basicTemp, ',');
//                }
//                else {
//                    $detailTemp = '';
//                    foreach ($array as $value) {
//                        $value['title']=$value['comment'];
//                        if ($value['title']) {
//                            $value['printElementType'] = [
//                                'title' => '表格',
//                                'type'  => 'tableCustom',
//                            ];
//                            $arr                       = array_merge($value, [
//                                'align'   => 'center',
//                                'width'   => 100,
//                                'checked' => true,
//                                'data'    => $value['title'],
//                            ]);
//                            $detailTemp                .= json_encode($arr,320) . ",\n";
//                        }
//                    }
//                    if ($detailTemp) {
//                        $detail .= <<<EOT
//{
//	tid: 'leftModule.detail',
//	title: '详情表',
//	type: 'table',
//	editable: true,
//	columnDisplayEditable: true,	//列显示是否能编辑
//	columnDisplayIndexEditable: true, //列顺序显示是否能编辑
//	columnTitleEditable: true, //列标题是否能编辑
//	columnResizable: true, //列宽是否能调整
//	columnAlignEditable: true, //列对齐是否调整
//	columns: [
//		[$detailTemp]
//	]
//}
//EOT;
//                    }
//                }
//            }
            $printData = null;
//halt($detail);
            $json      .= $basic .','. $detail . ']),';
            View::assign([
                'title'     => $info['name'],
                'id'        => $info['id'],
                'printJson' => $info['tplBody'] ? : '',
                'printData' => $printData ?: '{}',
                'json'      => $json]);
            return view();
        }


    }


    public function creatData()
    {
        //主表数据
//        $data=[
//            'printName'=>'打印标题',
//            'orderNum'=>'订单号',
//            'pName'=>'供应商',
//            'orderDate'=>'单据日期',
////            'saleUnit'=>'销售单位',
//            'taxStr'=>'税率',
////            'payTypeName'=>'付款方式',
//            'saleName'=>'采购人',
//            'contactName'=>'联系人',
//            'contactPhone'=>'联系电话',
////            'saveName'=>'收货人',
////            'savePhone'=>'收货电话',
//        ];
//        $baseTemp=[];
//        foreach ($data as $k=>$v){
//            $baseTemp[]=json_encode([
//                'text'=>$v,
//                'field'=>$k,
//                'title' => "标题：{$v}，字段名：{$k}" ,
//                'tid'   => 'leftModule.' . $k
//            ],320);
//        }
////
//        $baseTemp=implode(',',$baseTemp);
//        return $baseTemp;

        //子表
        $detail=[
            'k'=>'序号',
            'brand'=>'品牌',
            'mdName'=>'品名',
            'buyCode'=>'订货号',
            'specs'=>'型号',
            'unit'=>'单位',
            'bjNum'=>'采购数量',
            'noTaxPrice'=>'未税单价',
            'bjPrice'=>'含税单价',
            'bjMoney'=>'含税小计',
//            'noTaxMoney'=>'未税总额',
//            'taxMoney'=>'税额',
//            'bjTime'=>'货期',
//            'khlh'=>'客户料号',
//            'proCode'=>'项目编码',
            'remark'=>'备注',
            'saleContractOrderNum'=>'关联销售合同',
            'saleNum'=>'销售数量',
            'unBuyNum'=>'未采购数量',
        ];
        $detailTemp=[];
        foreach ($detail as $k=>$v){
            $detailTemp[]=json_encode([
                'name' => $k,
                'title' => '标题：'.$v.'#'.$k,
                'printElementType'=>[
                    'title' => '表格',
                    'type'  => 'tableCustom'

                ],
                    'align'   => 'center',
                    'width'   => 100,
                    'checked' => true,
                    'data'    => $k,],320);

        }
        $detailTemp=implode(',',$detailTemp);
        $detail1 = <<<EOT
{
	tid: 'leftModule.detail',
	title: '详情表',
	type: 'table',
	editable: true,
	columnDisplayEditable: true,	//列显示是否能编辑
	columnDisplayIndexEditable: true, //列顺序显示是否能编辑
	columnTitleEditable: true, //列标题是否能编辑
	columnResizable: true, //列宽是否能调整
	columnAlignEditable: true, //列对齐是否调整
	columns: [
		[$detailTemp]
	]
}
EOT;
        return $detail1;
    }
}